﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Xml.XPath;
using Sgml;
using LuaInterface;
using Common;
using System.Text.RegularExpressions;

namespace XPathTool
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		public string[] Match(string pattern,string input)
		{
			StringBuilder sb = new StringBuilder();
			Regex regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
			MatchCollection matchs = regex.Matches(input);

			if (matchs.Count == 0)
			{
				return null;
			}

			string[] arr = new string[matchs.Count];
			int i = 0;
			foreach (Match match in matchs)
			{
				arr[i] = match.Result("$1");
				i++;
			}
			return arr;
		}

		private void button1_Click(object sender, EventArgs e)
		{
			CrawlJobFileFieldInfo f = new CrawlJobFileFieldInfo();
			f.Lua = "";
			Form1 t = new Form1();
			Lua lua = new Lua();
			lua.RegisterFunction("matchs", t, t.GetType().GetMethod("Match"));
			lua.DoString(textBox2.Text);
			LuaFunction fun = lua.GetFunction("doData");
			object[] objRet = fun.Call(f, "a", "b");

			try
			{
				StringBuilder sb = new StringBuilder();
				XmlDocument doc = FromHtml(textBox2.Text.Trim());

				XPathNavigator nav = doc.CreateNavigator();
				XPathNodeIterator nodes = nav.Select(textBox1.Text.Trim());
				while (nodes.MoveNext())
				{
					sb.Append(nodes.Current.InnerXml);
					sb.AppendLine();
				}
				textBox3.Text = sb.ToString();
			}
			catch
			{
			}
		}

		private XmlDocument FromHtml(string html)
		{
			html = html.Replace("xmlns=\"http://www.w3.org/1999/xhtml\"", "");
			// setup SGMLReader
			Sgml.SgmlReader sgmlReader = new Sgml.SgmlReader();
			sgmlReader.DocType = "HTML";
			sgmlReader.WhitespaceHandling = WhitespaceHandling.All;
			sgmlReader.CaseFolding = Sgml.CaseFolding.ToLower;
			sgmlReader.InputStream = new StringReader(html);

			// create document
			XmlDocument doc = new XmlDocument();
			doc.PreserveWhitespace = true;
			doc.XmlResolver = null;
			doc.Load(sgmlReader);
			return doc;
		}
	}
}
